package com.aia.prm.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import com.aia.ilp.domain.SmsLog;
import com.aia.prm.config.AddressNotFoundException;
import com.aia.prm.config.ChinaAddress;
import com.aia.prm.config.CompanyCodes;
import com.aia.web1.domain.Aginf2;
import com.aia.web1.domain.Aginf2Key;
import com.aia.web1.domain.Aginf3;
import com.aia.web1.domain.Aginf3Key;
import com.aia.web1.domain.Qnpe;
import com.aia.web1.domain.QnpeExample;
import com.aia.web1.web.nmp.NmpAction;
import com.cfh.ahead.Constant;
import com.cfh.domain.User;
import com.cfh.domain.UserExample;
import com.cfh.domain.UserExample.Criteria;
import com.cfh.util.Tools;

@SuppressWarnings("rawtypes")
public class DefaultServiceImpl extends AbstractDefaultService implements DefaultService {
	private static final Logger logger = Logger.getLogger(DefaultServiceImpl.class);

	public void changePassword(User currentUser, String newPassword) {
		currentUser.setPASSWORD(newPassword);
		getUserDAO().updateByPrimaryKey(currentUser);
	}

	public User getUserByUsernameAndPassword(String username, String password) {
		if (logger.isDebugEnabled()) {
			logger.debug("getUserByUsernameAndPassword(String, String) - start"); //$NON-NLS-1$
		}

		Assert.hasText(username);
		Assert.hasText(password);
		UserExample ue = new UserExample();
		Criteria ct = ue.createCriteria();
		ct.andLOGIN_NAMEEqualTo(username);
		ct.andPASSWORDEqualTo(password);
		List list = getUserDAO().selectByExample(ue);
		if (list != null && list.size() > 0) {
			User returnUser = (User) list.get(0);
			if (logger.isDebugEnabled()) {
				logger.debug("getUserByUsernameAndPassword(String, String) - end"); //$NON-NLS-1$
			}
			return returnUser;
		} else {
			return null;
		}
	}

	public void updateNmp(NmpAction action) {
		ChinaAddress add = null;
		final String from = action.getFrom();
		if ("dm".equals(from) && StringUtils.isBlank(action.getAddress()) ) {
			action.setAddress("广东-广州");
			logger.debug("Setting default address for dm project");
		}
		if("recruitment".equalsIgnoreCase(from) == false){
			try {
				add = CompanyCodes.translateToAddress(action.getAddress());
			} catch (AddressNotFoundException e) {
				logger.error("传入的省市参数错误", e);
				action.addActionError("传入的省市参数错误");
				return;
			}
		}else{
			add = new ChinaAddress();
		}

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}

		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnpeExample example = new QnpeExample();
			com.aia.web1.domain.QnpeExample.Criteria criteria = example.createCriteria();
			criteria.andQNXE_PHOEqualTo(mobile);
			if (StringUtils.isNotBlank(from)) {
				criteria.andQNXE_FROMEqualTo(from);
			}
			List list = getQnpeDAO().selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已经提交过，请勿重复提交，感谢您的参与！");
				return;
			}
		}
		String code = action.getCode();
		if (StringUtils.isEmpty(code)) {
			code = "999999999";
		}
		code = StringUtils.leftPad(code, 9, "0");
		Qnpe record = new Qnpe();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_CODE(code);
		record.setQNXE_NAME(action.getName());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());
		if("recruitment".equalsIgnoreCase(from) == true){
			record.setQNXE_PROVINCE(action.getNew_sheng());
			record.setQNXE_CITY(action.getNew_shi());
			record.setQNXE_DISTRICT(action.getNew_qu());
			record.setQNXE_FREETEXT8(action.getNew_intr());
		}else{
			record.setQNXE_PROVINCE(add.getProvinceCode());
			record.setQNXE_CITY(add.getCityCode());
			record.setQNXE_DISTRICT(add.getDistCode());
		}
		record.setQNXE_FREETEXT3(add.getCompanyCode());
		record.setQNXE_FREETEXT4(add.getProviceName());
		
		
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_FROM(from);
		record.setQNXE_FREETEXT1(action.getEmail());
		record.setQNXE_FREETEXT2(action.getIdnumber());

		record.setQNXE_FREETEXT5(action.getLang()); // 常用语言
		record.setQNXE_FREETEXT6(action.getBirthm()); // 生日-月
		record.setQNXE_BIRTH(action.getBirthy()); // 生日-年
		record.setQNXE_SEX(action.getSex()); // 性别
		record.setQNXE_FREETEXT7(action.getAge()); // 年龄
		qnpeDAO.insert(record);
		removeCaptcha();

		logger.debug("print from=" + from);
		if ("xingfu".equals(from)) {
			try {// 发短信给agent
				Aginf2Key key2 = new Aginf2Key();
				key2.setAGI_CITYCODE(add.getCityCode());
				key2.setAGI_PROVINCECODE(add.getProvinceCode());
				key2.setAGI_CODE(code);
				Aginf2 aginf2 = aginf2DAO.selectByPrimaryKey(key2);
				if (aginf2 != null && StringUtils.isNotEmpty(aginf2.getAGI_PHONE()) && aginf2.getAGI_PHONE().length() == 11) {
					SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
					String today = formatter.format(new Date());

					String msg = record.getQNXE_NAME() + " " + record.getQNXE_PHO() + " " + today + "参与了[幸福人生 至真生活]活动";
					sendSMS(msg, aginf2.getAGI_PHONE(), from, false);
				}
			} catch (Exception e) {
				logger.error("发AGENT短信出错-xingfu", e);
			}
		} else if ("JS-summer".equals(from)) {
			try {// 发短信给agent
				Aginf3Key key2 = new Aginf3Key();
				key2.setAGI_CITYCODE(add.getCityCode());
				key2.setAGI_PROVINCECODE(add.getProvinceCode());
				key2.setAGI_CODE(code);
				Aginf3 aginf2 = aginf3DAO.selectByPrimaryKey(key2);
				if (aginf2 != null && StringUtils.isNotEmpty(aginf2.getAGI_PHONE()) && aginf2.getAGI_PHONE().length() == 11) {
					SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
					String today = formatter.format(new Date());

					String msg = record.getQNXE_NAME() + " " + record.getQNXE_PHO() + " " + today + "参与了友邦江苏 [“悦”动夏日，“佑”惑无限 ]活动";
					sendSMS(msg, aginf2.getAGI_PHONE(), from, false);
				}
			} catch (Exception e) {
				logger.error("发AGENT短信出错-JS-summer", e);
			}
		} else if ("xingui".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else if ("dm".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else if ("SOS".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else {
			logger.debug("else > skip send sms for:" + from);
		}
	}

	private void removeCaptcha() {
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				session.setAttribute(Constant.CAPTCHA_SESSION_HOLDER, "");
			}
		} catch (Exception e) {
			logger.warn("removeCaptcha:" + e, e);
		}
	}

	private int sendSMS(String msg, String mobile, String remark, boolean isThrowException) {
		try {
			{// 插入SMSLOG表
				SmsLog smslog = new SmsLog();
				smslog.setSMSLOG_GUID(Tools.GUID());
				smslog.setSMSLOG_DATE(Tools.getToday());
				smslog.setSMSLOG_TIME(Tools.getTime());
				smslog.setSMSLOG_MOBILE(mobile);
				smslog.setSMSLOG_FREETEXT1(remark);
				smsLogDAO.insertSelective(smslog);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("Print SMS>" + msg);
			}

			String sql = "INSERT INTO TT_AIA_SMS_MT (EXTEND_TYPE, SP_SERVICE_CODE, PRIORITY, PARAM_ONE, PARAM_TWO, DESTINATION_ADDR, CONTENT) VALUES (- 1, '03', 9, '0986', 'T04W02', ?, ?)";
			return getJdbcTemplate().update(sql, new Object[] { mobile, msg });
		} catch (RuntimeException e) {
			logger.error("发短信失败", e);
			if (isThrowException) {
				throw e;
			} else {
				return 0;
			}
		}

	}
}
